package com.studentexam.student.controller;

import com.studentexam.student.model.Role;
import com.studentexam.student.service.RoleService;
import com.studentexam.student.tool.ResponseMessage;
import com.studentexam.student.tool.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags="role")
@CrossOrigin
@RestController
public class RoleController {
    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "角色添加方法")
    @RequestMapping(value = "/addrole", method = RequestMethod.GET)
    public ResponseMessage add(Role role) {
        int isAdd = 0;
//        1.判断是否空对象
        if (role != null) {
//        2.判断是否空字段
            if (role.getRolename() != null) {
//               3.添加数据
                isAdd = roleService.addRole(role);
                if (isAdd==1){
                    return Result.success("保存成功");
                }else if (isAdd==-1){
                    return Result.success("已重复，不允许添加");
                }else return Result.error("保存失败");
            }
        }
        return Result.error("保存失败");
    }


    @ApiOperation(value = "角色删除方法")
    @RequestMapping(value = "/delrole", method = RequestMethod.GET)
    public ResponseMessage delete(int roleid){
        if (roleid!=0){
            int isDel=0;
            isDel=roleService.delRole(roleid);
            if (isDel>0){
                return Result.success("删除角色成功");
            }else return Result.error("删除角色失败");
        }else return Result.error("删除失败，id不能为0");
    }

    @ApiOperation(value = "角色更新方法")
    @RequestMapping(value = "/updaterole")
    public ResponseMessage update(Role role) {
        if (role != null) {
            if (role.getRoleid() != 0) {
                if (roleService.updateRole(role) > 0) {
                    return Result.success("更新角色信息成功");
                } else return Result.error("更新角色信息失败");
            } else return Result.error("更新角色信息失败，id不能为0");
        } else return Result.error("更新角色信息失败，role不能为空");
    }

    @ApiOperation(value = "根据条件获取角色信息")
    @RequestMapping(value = "/getByRoleid",method = RequestMethod.GET)
    public ResponseMessage getByRoleid(int roleid){
        Map<String, List> map=new HashMap<>();
        List<Role> roleList=roleService.getByRoleid(roleid);
        map.put("list",roleList);
        return Result.success("查询成功",map);
    }
}
